<script lang="ts" setup>
import {menus} from "../routes"
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import {useRoute, useRouter} from 'vue-router'
import {UserFilled} from "@element-plus/icons-vue";
import {chatSendApi} from "../serve.ts";

const dialogVisible = ref(false)
const inputMsg = ref('')
const messages = ref<Array<{ content: string, isUser: boolean, time: string }>>([])
let socket: WebSocket | null = null
const
    route = useRoute(),
    router = useRouter()
;

function contactService() {
  dialogVisible.value = true
  initWebSocket()
}

const messageBody = ref({
  "message": "",
  "sender": "",
  "receiver": "",
  "type": ""
})

// 初始化WebSocket连接
function initWebSocket() {
  if (socket) return
  let token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.error('请先登录');
    router.push('/login')
    return
  }
  // 替换为你的WebSocket服务地址
  socket = new WebSocket('ws://127.0.0.1:9876/ws?token=' + token)

  socket.onopen = () => {
    ElMessage.success('已连接客服')
  }

  socket.onmessage = (event) => {
    let res = JSON.parse(event.data)
    if (res.type !== 'system') {
      messages.value.push({
        content: res.message,
        isUser: false,
        time: new Date().toLocaleTimeString()
      })
    } else {
      messageBody.value = res;
    }

  }

  socket.onerror = (error) => {
    ElMessage.error('连接错误: ' + error)
  }

  socket.onclose = () => {
    ElMessage.warning('连接已关闭')
    socket = null
  }
}

function closeWebSocket() {
  if (socket?.readyState === WebSocket.OPEN) {
    const data = messageBody.value;
    data.type = "close";
    chatSendApi({...data})
        .then((r: any) => {
          console.log(r);
        });
    dialogVisible.value = false;
  }
}

// 发送消息
function handleSendMessage() {
  if (!inputMsg.value.trim()) return
  if (socket?.readyState === WebSocket.OPEN) {
    // socket.send(inputMsg.value)
    let data = messageBody.value;
    data.message = inputMsg.value;
    data.type = "normal";
    chatSendApi({...data}).then((r: any) => {
      messages.value.push({
        content: inputMsg.value,
        isUser: true,
        time: new Date().toLocaleTimeString()
      })
      inputMsg.value = ''
    })
  } else {
    ElMessage.error('连接尚未建立')
  }
}

function clearMessage() {
  if (socket?.readyState === WebSocket.OPEN) {
    messages.value = []
  }
}
</script>

<template>
  <!-- 在原有template中添加对话框 -->
  <el-dialog
      v-model="dialogVisible"
      title="在线客服"
      width="40%"
      @close="closeWebSocket()"
  >
    <div class="chat-container">
      <div class="message-area">
        <div
            v-for="(msg, index) in messages"
            :key="index"
            :class="['message-item', msg.isUser ? 'user-message' : 'service-message']"
        >
          <div class="message-content">{{ msg.content }}</div>
          <div class="message-time">{{ msg.time }}</div>
        </div>
      </div>
      <div class="toolbox">
        <el-button type="warning" @click="clearMessage">清空消息</el-button>
        <el-button type="danger" @click="closeWebSocket">结束当前会话</el-button>
      </div>
      <div class="input-area">
        <el-input
            v-model="inputMsg"
            placeholder="输入消息..."
            @keyup.enter="handleSendMessage"
        >
          <template #append>
            <el-button @click="handleSendMessage">发送</el-button>
          </template>
        </el-input>
      </div>
    </div>
  </el-dialog>
  <el-scrollbar>
    <div top>
      <div top-left>
        <img alt="logo" src="/icon.svg" style="width: 25px;height: 25px;"/>
        <div nome>春屿的花店</div>
      </div>
      <div top-center>
        <div v-for="(i,index) in menus" :key="index">
          <div :class="{textBa:route.path == i.path}" item style="margin: 0 12px;position: relative;"
               @click="router.push(i.path).catch(()=>true)">
            {{ i['meta']['title'] }}
            <div v-if="route.path == i.path" itemAb/>
          </div>
        </div>
      </div>
      <div top-right>
        <img alt="logo" src="/vip.svg" style="width: 30px;height: 30px;cursor: pointer;"
             @click="router.push('/vip').catch(()=>true)"/>
        <div nome style="cursor: pointer;" @click="router.push('/userInfo').catch(()=>true)">
          <el-icon>
            <UserFilled/>
          </el-icon>
          个人中心
        </div>
      </div>
    </div>
    <div
        style="height: calc(100% - 60px);overflow: hidden;position: absolute;transition: all 0.3s;top: 60px;width: 100%;">
      <router-view v-slot="{ Component }">
        <transition name="slide">
          <!--          <KeepAlive>-->
          <component :is="Component"/>
          <!--          </KeepAlive>-->
        </transition>
      </router-view>
    </div>
    <div class="service" @click="contactService">
      <div id="top">
        <svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="64"
             height="64">
          <path
              d="M516.667511 807.863307c5.004179 0 10.095748-0.308016 15.221701-0.916884 49.157857-5.899573 90.900417-40.259787 106.306927-87.609664 1.163296-3.541463-0.515747-7.336502-3.906784-8.892339-3.352356-1.561567-7.409566-0.212029-9.306369 2.965546-0.179079 0.302285-19.710133 31.848813-95.745574 42.117909-11.382251 1.527184-22.457919 2.328025-32.956236 2.328025-53.270939-0.034383-77.00963-20.112702-77.22739-20.297512-2.680452-2.383897-6.772045-2.445501-9.519831-0.123206-2.775006 2.322294-3.413959 6.358015-1.521454 9.446767C431.202495 784.477044 472.816118 807.863307 516.667511 807.863307L516.667511 807.863307zM516.667511 807.863307M925.504492 336.633827c-0.670471 0-1.280772 0.123206-1.918292 0.123206C879.03425 143.879099 708.803342 0 504.703612 0c-209.712777 0-383.850469 151.824469-422.446972 352.685021C44.728879 359.438442 16.165088 392.423331 16.165088 432.3135l0 159.653796c0 44.746787 35.883101 81.032457 80.188637 81.032457 24.992242 0 47.051889-11.802012 61.726326-29.927655 35.457609 93.781437 107.642139 169.397117 198.995267 209.293016 0.21776-0.475633 1.946945-3.83945 4.028557-6.519902 1.438361-1.858122 3.050071-3.379576 4.432559-3.379576 1.432631 0 2.747786 0.520045 3.872401 1.313722-21.142764-15.741746-97.51344-96.656727-114.056026-209.572379-7.257707-49.699391 29.967769-98.487629 73.322038-106.557638 69.600064-12.959577 138.836239-27.722836 208.436303-40.437434 44.243933-8.070009 74.479604-32.340205 92.969135-72.750419 4.332275-9.446767 10.588573-28.546599 13.459565-56.091789 0.760727-4.095891 4.118813-7.240515 8.422436-7.240515 2.870992 0 5.310762 1.465581 6.928202 3.575846l1.919725-1.191949c27.432012 39.827133 81.833297 128.012715 89.645432 220.999042 8.971133 106.311225 3.966954 179.124679-77.406468 253.615744-0.095986 0.094554-0.219192 0.212029-0.336668 0.308016-1.130346 1.219169-1.802249 2.807956-1.802249 4.554333 0 2.289344 1.220601 4.24775 2.988468 5.439699 0.671904 0.275065 1.343808 0.643251 2.015711 0.918316 0.547265 0.123206 1.068742 0.302285 1.61744 0.302285 0.552995 0 1.04009-0.179079 1.527184-0.302285 1.158998-0.610301 2.254961-1.315155 3.385306-1.925456 82.293172-45.335598 145.423475-121.045832 174.596134-212.108136 11.809175 17.543995 30.298706 30.16977 51.776705 34.573676C874.366739 816.570836 734.623645 914.634406 561.493092 929.519439c-10.375111-25.73721-35.916051-44.014712-65.91104-44.014712-39.173853 0-70.938141 31.026483-70.938141 69.264828 0 38.239778 31.758557 69.230445 70.938141 69.230445 31.585209 0 58.037302-20.291781 67.220464-48.172207 200.406408-16.290443 361.057315-135.410819 394.595199-320.495243 29.626803-12.38366 50.432898-41.450304 50.432898-75.380729L1007.830614 418.406954C1007.830614 373.256165 970.969026 336.633827 925.504492 336.633827L925.504492 336.633827zM851.573585 383.038168C799.305488 241.448412 663.860285 140.301821 504.524533 140.301821c-158.669579 0-293.627687 100.289878-346.382879 240.96275-2.624579-3.211958-5.703303-5.959744-8.724721-8.741912C179.282985 201.099801 326.816725 70.76336 504.703612 70.76336c177.035904 0 324.10977 129.054237 354.955741 299.286578C856.610715 374.145829 853.801326 378.420799 851.573585 383.038168L851.573585 383.038168zM851.573585 383.038168M357.086779 852.365114c-0.005731 0-0.005731 0-0.011461 0C357.042368 852.436745 357.042368 852.448206 357.086779 852.365114L357.086779 852.365114zM357.086779 852.365114"
              fill="#272636"></path>
        </svg>
      </div>
      <div id="bottom">
        联系客服
      </div>
    </div>
  </el-scrollbar>
</template>

<style lang="scss" scoped>
[top] {
  user-select: none;
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 60px;
}

.toolbox {
  width: 100%;
  height: 40px;
}

.service {
  cursor: pointer;
  position: absolute;
  width: 100px;
  height: 100px;
  //background-color: #ffffff;
  //top: 0;
  bottom: 5%;
  right: 1%;
}

#top, #bottom {
  margin: 0 auto;
  text-align: center;
}

[top-left] {
  display: flex;
  width: 140px;
  align-items: center;
  justify-content: end;
  margin-right: 10px;
  font-size: 15px;

  [nome] {
    margin-left: 8px;
  }
}

[top-center] {
  flex: 1;
  display: flex;
  justify-content: center;
  font-size: 14px;
  letter-spacing: 1px;

  [item] {
    cursor: pointer;

    &:hover {
      color: #6ce1e1;
    }

    [itemAb] {
      position: absolute;
      background-color: #FA9BB6;
      width: 100%;
      height: 2px;
      margin-top: 5px;
    }
  }

  .textBa {
    color: #FA9BB6;
  }
}

[top-right] {
  display: flex;
  width: 140px;
  align-items: center;
  justify-content: start;
  margin-left: 10px;
  font-size: 14px;

  [nome] {
    display: flex;
    align-items: center;
    margin-left: 10px;
  }
}

.chat-container {
  height: 60vh;
  display: flex;
  flex-direction: column;

  .message-area {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    border: 1px solid #eee;
    border-radius: 4px;
    margin-bottom: 10px;

    .message-item {
      margin: 10px 0;
      max-width: 70%;
      padding: 8px 12px;
      border-radius: 8px;
      position: relative;

      .message-time {
        font-size: 12px;
        color: #999;
        margin-top: 4px;
      }
    }

    .user-message {
      background: #e6f4ff;
      margin-left: auto;
      border-bottom-right-radius: 2px;
    }

    .service-message {
      background: #f5f5f5;
      margin-right: auto;
      border-bottom-left-radius: 2px;
    }
  }

  .input-area {
    :deep(.el-input-group__append) {
      padding: 0;

      .el-button {
        height: 5px;
        line-height: 5px;
        padding: 20px 40px;
      }

      .el-button:hover {
        color: #409eff;
      }
    }
  }
}
</style>